package com.pkq.arraylist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author: little_lunatic
 * @Date: 2021/9/7 16:05
 * @Description: 使用JUC包下的CopyOnWriteArrayList 低效率 解决 ArrayList 多线程下的线程安全问题
 */
public class ArrayListDemo {
    public static void main(String[] args) {

        // java.util.ConcurrentModificationException 多线程情况下使用ArrayList引发线程安全问题，ConcurrentModificationException
        // 方法2. 使用 Collections 工具类
        List<Object> list = Collections.synchronizedList(new ArrayList<>());

        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString());
                System.out.println(list);
            }, i + "线程-->    ").start();
        }

        // 方法1. vector可以解决，但是效率低
/*        Vector<Object> vector = new Vector<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                vector.add(UUID.randomUUID().toString());
                System.out.println(Thread.currentThread().getName() + vector);
            }, i + "v线程-->    ").start();
        }*/

        // 方法3. 使用JUC包下的CopyOnWriteArrayList
        CopyOnWriteArrayList<Object> writeArrayList = new CopyOnWriteArrayList<>();


        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                writeArrayList.add(UUID.randomUUID().toString());
                System.out.println(Thread.currentThread().getName() + writeArrayList);
            }, i + " ww线程-->    ").start();
        }
    }
}
